# acts like a history
class Winstreak < ActiveRecord::Base
  belongs_to :user
  belongs_to :prize
  has_many   :bets,:order=>"#{Bet.table_name}.updated_at ASC" do
     def win
      scoped(
	:conditions=>"win = true"
      )
     end
  end
  has_many   :matches,:through=>:bets,:source=>:match


  # 比赛结束了，需要重新计算
  # 比如 超过了连胜，那么用户就需要重新开启一个winstreak了
  def calc
    if goal?
      # send user mini-feed to facebook
      WinstreakPublisher.deliver_winstreak_goal(user)
      self.got_prize = true
      self.got_prize_at = Time.now
      user.reset_winstreak
    else
      # send user mini-feed when winstreak greate than 7 
      if [2,4,6,8,10,11,12].include?(streak_count.to_i)
        WinstreakPublisher.deliver_winstreak_remain(user) 
      end
      # 超过了自己的最高记录，发送一条 feed
      if user.best_winstreak.streak_count == streak_count
        if user.matches.next
          WinstreakPublisher.deliver_winstreak_new_record user
        end
      end
    end
    # self.streak_count = bets.win(true).count
    save
  end

  # 距离奖品剩下的 streak
  def streak_remain
    user.prize.streak.to_i - streak_count.to_i
  end

  def half_win
    bets.played(true).win(true).half_streak.first
  end

  def half_loss
    bets.played(true).win(false).half_streak.first
  end

  def half_loss_full?
    bets.played(true).win(false).half_streak.count >= 2
  end

  def goal?
    streak_remain.zero?
  end
end
